<template>
	<view class="arc-container drawInfo" :style="{ height: containerHeight + 'rpx' }">
		<view class="arc-text drawInfo">
			<text v-for="(char, index) in charElements" :key="index" class="char drawInfo" data-type="text"
				:data-word="char.text" data-color="red" :style="{
																  fontSize: fontSize + 'rpx',
																  left: char.x + 'rpx',
																  top: char.y + 'rpx',
																  transform: 'translate(-50%, -50%) rotate(' + char.rotation + 'deg)'
																}"
			>{{ char.text }}</text>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		watch,
		onMounted
	} from 'vue'

	// 组件属性
	const props = defineProps({
		text: {
			type: String,
			default: "CSS3实现弧形排列文字，每个字符与弧线切线垂直！"
		},
		radius: {
			type: Number,
			default: 300
		},
		fontSize: {
			type: Number,
			default: 32
		},
		rotation: {
			type: Number,
			default: 0
		},
		spacing: {
			type: Number,
			default: 5
		}
	})

	// 容器高度
	const containerHeight = ref(props.radius * 2)

	// 响应式字符元素数组
	const charElements = ref([])

	// 计算字符位置和样式
	const calculateArcText = () => {
		const characters = props.text.split('')
		const totalChars = characters.length

		if (totalChars === 0) {
			charElements.value = []
			return
		}

		// 计算总弧长和圆弧角度
		const totalArcLength = (props.fontSize + props.spacing) * totalChars
		const arcAngle = totalArcLength / props.radius

		// 计算每个字符的角度增量
		const angleIncrement = totalChars > 1 ? arcAngle / (totalChars - 1) : 0

		// 起始角度（从左侧开始）
		let currentAngle = -arcAngle / 2

		// 生成字符元素数组
		charElements.value = characters.map(char => {
			// 计算字符位置
			const x = props.radius * Math.sin(currentAngle) + props.radius
			const y = -props.radius * Math.cos(currentAngle) + props.radius + 20

			// 计算字符旋转角度（与切线垂直）
			const charRotation = (currentAngle * 180 / Math.PI) + props.rotation

			// 更新角度
			currentAngle += angleIncrement

			return {
				text: char,
				x: x,
				y: y,
				rotation: charRotation
			}
		})

		// 更新容器高度
		containerHeight.value = props.radius * 2
	}

	// 监听属性变化
	watch(() => [props.text, props.radius, props.fontSize, props.rotation, props.spacing], () => {
		calculateArcText()
	})

	// 组件挂载时计算
	onMounted(() => {
		calculateArcText()
	})
</script>

<style scoped>
	.arc-container {
		position: relative;
		width: 100%;
		display: flex;
		justify-content: center;
	}

	.arc-text {
		position: relative;
		width: 100%;
	}

	.char {
		position: absolute;
		transform-origin: center;
		white-space: nowrap;
		font-weight: bolder;
		background: linear-gradient(to bottom, #ca73de, #8e38e7, #630eed) 0% 100%;
		-webkit-background-clip: text;
		background-clip: text;
		color: transparent;
		font-family: 'fzround';
	}
</style>